//
//  ViewController.m
//  19-JSON
//
//  Created by mafeng on 16/8/9.
//  Copyright © 2016年 mafeng. All rights reserved.
//

#import "ViewController.h"
#import "LabelWaterLayout.h"
#import "MyCollectionViewCell.h"
#import "ContentTitle.h"
@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, LabelWaterLayoutDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (nonatomic, strong) NSMutableArray<ContentTitle *> *contentTitleArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // Do any additional setup after loading the view, typically from a nib.
    
    [self handleData];
    NSLog(@"%@", _myCollectionView.collectionViewLayout);
    LabelWaterLayout *layout = (LabelWaterLayout *)self.myCollectionView.collectionViewLayout;
    layout.delegate = self;
    
//    self.myCollectionView = [UICollectionView alloc] initWithFrame:<#(CGRect)#> collectionViewLayout:<#(nonnull UICollectionViewLayout *)#>
//    
}

- (void)handleData {
    self.contentTitleArray = [NSMutableArray array];
    // JSON解析
    // 通过一个Data, 将对应的JSON格式转化成OC认识的内容
    // 数组/字典
    
    // 获取json的data
    NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"FirstJSON" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:dataPath];
    // json解析
    NSError *error = nil;
    NSDictionary *jsonDic =  [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        NSLog(@"%@", jsonDic);
    NSArray *list = jsonDic[@"tabs"][@"list"];
    for (NSDictionary *contentDic in list) {
        ContentTitle *contentTitle = [ContentTitle contentTitleWithDict:contentDic];
        [_contentTitleArray addObject:contentTitle];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _contentTitleArray.count;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout height:(CGFloat)height widthForItemAtIndexPath:(NSIndexPath *)indexPath {
    ContentTitle *contentTitle = _contentTitleArray[indexPath.row];
    CGRect newRect = [contentTitle.title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
    CGFloat width = ceil(CGRectGetWidth(newRect));
    return width;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.contentTitle = _contentTitleArray[indexPath.row];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
